<template>
    <el-dialog :close-on-click-modal="false" v-model="visible" @close="handleClose" title="商品信息" destroy-on-close fullscreen class="full-dialog">
        <template #header>
            <div class="flex">
                <el-button type="primary">基本信息</el-button>
            </div>
        </template>
        <el-scrollbar style="height: calc(100vh - 145px)" v-loading="loading">
            <div class="mx-4 my-8">
                <!---------------------基本信息开始-------------------->
                <el-form ref="formRef" :model="form" label-position="right" label-width="180px" style="max-width: 600px" :rules="rules">
                    <el-form-item label="商品分类选择" prop="category_ids" required>
                        <el-cascader v-model="form.category_ids" :options="options" :props="{ value: 'id', label: 'name', children: 'children' }" />
                    </el-form-item>
                    <el-form-item label="商品中文名称" prop="title">
                        <el-input v-model="form.title"></el-input>
                    </el-form-item>

                    <el-form-item label="商品第二名称" prop="sub_title">
                        <el-input v-model="form.sub_title"></el-input>
                    </el-form-item>
                    <el-form-item label="商品IP缩写" required>
                        <el-input style="width: 100px" v-model="ipNoe"></el-input>&nbsp;&nbsp;&nbsp;&nbsp;
                        <el-input style="width: 100px" v-model="ipTwo"></el-input>
                    </el-form-item>
                    <el-form-item label="商品稀有度" prop="rarity">
                        <el-input v-model="form.rarity"></el-input>
                        <!-- <el-select v-model="form.Rarity"></el-select> -->
                    </el-form-item>
                    <el-form-item label="商品编号" prop="ean">
                        <el-input v-model="form.ean"></el-input>
                    </el-form-item>
                    <el-form-item label="商品分类" required>
                        <template #default>
                            <el-form :model="specform" :rules="specrules">
                                <el-form-item label="是否评级卡">
                                    <el-radio-group v-model="tagRadio" @change="changeRadio">
                                        <el-radio-button v-for="(item, index) in spec_type" :label="item.spec_name" />
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item label="卡牌品相" style="margin: 20px 0" prop="spec_name" v-if="tagRadio == '非评级卡'">
                                    <el-select v-model="spec_name" @change="selectChange">
                                        <el-option v-for="item in spec_condition" :key="item.id" :label="item.spec_name" :value="item.spec_name" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="鉴定平台" style="margin: 20px 0" prop="spec_name" v-else>
                                    <el-select v-model="spec_name" @change="selectChange">
                                        <el-option v-for="item in spec_company" :key="item.id" :label="item.spec_name" :value="item.spec_name" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="评分" required v-if="tagRadio != '非评级卡'">
                                    <el-input v-model="specform.score"></el-input>
                                </el-form-item>
                                <el-form-item label="收购价格" style="margin: 20px 0" prop="money_price">
                                    <el-input v-model="specform.money_price"></el-input>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="handleSpec">新增</el-button>
                                </el-form-item>
                            </el-form>
                        </template>
                    </el-form-item>
                    <el-form-item label="已选分类" v-if="form.skus.length">
                        <!-- <span v-for="(item,index) in form.skus">{{ index }}</span> -->
                        <!-- <div v-for="(item, index) in form.skus">规格：{{ item.product_spec }}价格：{{ item.money_price }}</div> -->
                        <el-tag
                            style="margin-bottom: 20px"
                            v-for="(item, index) in form.skus"
                            :key="index"
                            closable
                            :disable-transitions="false"
                            @close="delTags(index)"
                        >
                            规格：{{ item.product_spec }}&nbsp;&nbsp;&nbsp;价格：{{ item.money_price }}元
                        </el-tag>
                    </el-form-item>
                    <!-- <el-form-item label="商品求购金额" prop="PurchasePrice">
                        <el-input v-model="form.money_price"></el-input>
                    </el-form-item> -->
                    <el-form-item label="商品图片" prop="thumb">
                        <ImgHub v-model="coverImgList" :limit="1" :deleteAll="false" :multiple="false"></ImgHub>
                    </el-form-item>
                    <el-form-item label="是否上架">
                        <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
                        <!-- <div class="flex flex-wrap flex-row gap-2">
                            <InputTags v-model="tags"></InputTags>
                        </div> -->
                    </el-form-item>
                    <el-form-item label="商品现存库存数量">
                        <el-input v-model="form.stock"></el-input>
                    </el-form-item>
                    <el-form-item label="商品列表排序">
                        <el-input v-model="form.list_weight"></el-input>
                    </el-form-item>
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSave"><Icon name="fa fa-save" class="mr-1 text-white text-base"></Icon> 保存 </el-button>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, watch, nextTick, onMounted } from 'vue'
import { formData } from '/@/api/product'
import ImgHub from '/@/components/imgHub/index.vue'
import { ElMessage, selectGroupKey } from 'element-plus'
import createAxios from '/@/utils/axios'
import lo from 'lodash'
const props = defineProps({
    modelValue: Boolean,
    categoryList: Array,
    data: Object,
})
const id = ref(5)
// 编辑商品规格
const delTags = (index: any) => {
    // console.log(index,'item')
    form.value.skus.splice(index, 1)
    // console.log('skus', form.value.skus)
}

// 监听弹窗显示与隐藏
watch(
    () => props.modelValue,
    (val) => {
        visible.value = val
        if (val) {
            nextTick(async () => {
                formRef.value.resetFields()
                // tagActive.value = 0
                if (props.data?.id) {
                    // await getGoodsTree()
                    await getProductInfo()
                }
            })
        } else {
            loading.value = false
            form.value = {
                category_ids: '',
                title: '',
                sub_title: '',
                tags: '',
                rarity: '',
                ean: '',
                thumb: '',
                status: '',
                stock: '',
                list_weight: '',
                skus: [],
            } // 表单数据
            coverImgList.value = []
            ipNoe.value = ''
            ipTwo.value = ''
            spec_name.value = ''
            tagRadio.value = '非评级卡'
            specform.value = {
                product_spec: '',
                money_price: '',
                score: '',
            }
        }
    }
)
// 获取商品信息
const getProductInfo = () => {
    loading.value = true
    createAxios({ url: '/admin/wms.products/detail', method: 'get', params: { id: props.data?.id } })
        .then((res) => {
            console.log('res', res)
            let data = res.data
            form.value = {
                category_ids: data.category_ids ? lo.map(data.category_ids.split(','), lo.unary(parseInt)) : [],
                title: data.title,
                sub_title: data.sub_title,
                tags: data.tags,
                rarity: data.rarity,
                ean: data.ean,
                thumb: data.thumb,
                status: data.status,
                stock: data.stock,
                list_weight: data.list_weight,
                skus: data.skus,
            }
            coverImgList.value = data.thumb?.split(',')
            console.log('skus', form.value.skus)
            let tags: string[] = data.tags.split(',')
            console.log('tags', tags)
            ipNoe.value = tags[0]
            ipTwo.value = tags[1] ? tags[1] : ''
        })
        .finally(() => {
            loading.value = false
        })
}
// ------------------------------------------------------------------<分割线>-------------------------------------
let visible = ref(false)
let loading = ref(false)
let formRef = ref() // 表单实例
let coverImgList = ref([])
const emits = defineEmits(['close', 'update'])
const handleClose = () => {
    emits('close', false) // 可以更新 v-model 绑定的值
}
// ------------------------------------------------------------------<分割线>-------------------------------------
const ipNoe = ref('')
const ipTwo = ref('')
// 商品规格数据
const tagRadio = ref('非评级卡')
const spec_name = ref('')
// const product_spec = ref<string[]>([])
// const money_price = ref('')
const specform = ref({
    product_spec: '',
    money_price: '',
    score: '',
})
// const specArr = ref([])
const selectChange = () => {
    // console.log(spec_name.value)
    specform.value.money_price = ''
}
const changeRadio = () => {
    // console.log('value', tagRadio.value)
    spec_name.value = ''
    specform.value.money_price = ''
    specform.value.score = ''
}
// 商品规格表单验证
const specrules = reactive({
    // spec_name: [{ required: true, message: '请选择卡牌品相', trigger: 'blur' }],
    // money_price: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
})

// 保存规格数据
const handleSpec = () => {
    if (!spec_name.value) {
        ElMessage({ type: 'warning', message: '请选择商品品相' })
        return false
    } else if (!specform.value.score && tagRadio.value != '非评级卡') {
        ElMessage({ type: 'warning', message: '请填写评分' })
        return false
    } else if (!specform.value.money_price) {
        ElMessage({ type: 'warning', message: '请填写价格' })
        return false
    }
    if (tagRadio.value == '非评级卡') {
        specform.value.product_spec = tagRadio.value + ',' + spec_name.value
    } else {
        specform.value.product_spec = tagRadio.value + ',' + spec_name.value + ',' + specform.value.score
    }
    console.log('before', form.value.skus)
    form.value.skus.push({ ...specform.value })
    console.log('after', form.value.skus)
    // specform.value.money_price = ''
    // specform.value.score = ''
    // spec_name.value = ''
}
// 表单数据
const form = ref<formData>({
    category_ids: '',
    title: '',
    sub_title: '',
    tags: '',
    rarity: '',
    ean: '',
    thumb: '',
    status: '',
    stock: '',
    list_weight: '',
    skus: [],
})
const rules = reactive({
    category_ids: [{ required: true, message: '请选择分类', trigger: 'change' }],
    title: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
    tags: [{ required: true, message: '请选择商品ip', trigger: 'change' }],
    rarity: [{ required: true, message: '请选择商品稀有度', trigger: 'blur' }],
    ean: [{ required: true, message: '请输入商品编号', trigger: 'blur' }],
    Condition: [{ required: true, message: '请选择商品类别', trigger: 'blur' }],
    PurchasePrice: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
    thumb: [{ required: true, message: '请上传商品图片', trigger: 'blur' }],
}) // 表单规则
// 获取商品规格
const spec_type: any = ref([])
const spec_condition: any = ref([])
const spec_company: any = ref([])
const getGoodsTags = async () => {
    await createAxios({ url: '/admin/wms.Specs/get', method: 'get' }).then((res) => {
        spec_type.value = res.data.spec_type
        spec_condition.value = res.data.spec_condition
        spec_company.value = res.data.spec_company
        // options.value = res.data.list
    })
}
getGoodsTags()
// 获取商品分类数据
const options = ref([])
const getGoodsTree = async () => {
    await createAxios({ url: '/admin/xmwms.Category/index', method: 'get' }).then((res) => {
        options.value = res.data.list
    })
}
getGoodsTree()
// 保存
const handleSave = async () => {
    console.log('image',coverImgList.value)
    if (!form.value.skus.length) {
        ElMessage({ type: 'warning', message: '请添加商品规格' })
        return false
    }
    form.value.category_ids = JSON.stringify(form.value.category_ids).slice(1, -1)
    if (ipNoe.value && ipTwo.value) {
        form.value.tags = ipNoe.value + ',' + ipTwo.value
    } else {
        form.value.tags = ipNoe.value
    }
    // console.log('form', form.value)
    form.value.thumb = coverImgList.value.join(',')
    console.log(form.value)
    await formRef.value.validate(async (valid: any) => {
        if (valid) {
            let url
            loading.value = true

            let params:any = {
                category_ids: form.value.category_ids,
                title: form.value.title,
                sub_title: form.value.sub_title,
                tags: form.value.tags,
                rarity: form.value.rarity,
                ean: form.value.ean,
                // money_price: form.value.PurchasePrice,
                thumb: form.value.thumb,
                status: form.value.status,
                stock: form.value.stock,
                list_weight: form.value.list_weight,
                skus: form.value.skus,
            }
            if (props.data?.id) {
                url = '/admin/wms.Products/edit'
                params.id = props.data.id
            } else {
                url = '/admin/wms.Products/add'
            }
            await createAxios({ url: url, method: 'post', data: params })
                .then((res) => {
                    ElMessage({ type: 'success', message: res.msg })
                    emits('update')
                    handleClose()
                })
                .catch((err) => {
                    // ElMessage({ type: 'error', message: res.msg })
                })
                .finally(() => {
                    loading.value = false
                })
        }
    })
}
</script>
